<script setup>
import {computed, defineExpose, onBeforeUnmount, onMounted, ref, watch} from 'vue'
import TableColumnConfig from "~/components/lib/TableColumnConfig";
// import { ElTable } from 'element-plus'
// import 'element-plus/dist/index.css'
import {categoryData} from "~/logic";
import ClipboardJS from 'clipboard'
import {message} from 'ant-design-vue'
import {CheckCircleOutlined, DownOutlined, SearchOutlined, SettingOutlined} from '@ant-design/icons-vue'
// import {WorkBook, WorkSheet} from 'xlsx'
import {utils, writeFileXLSX} from 'xlsx'
import moment from 'moment'
import {uid} from 'uid';

const props = defineProps({
  size: {
    type: String,
    default: 'small'
  },
  scroll: {
    type: Object,
    default: () => {
      return {
        x: '100%',
        y: 700
      }
    }
  },
  pagination: {
    type: Boolean,
    default: false,
  },
  rowKey: {
    type: String,
    default: 'key',
  },
  selectedRows: {
    type: [Boolean, Array],
    default: () => false,
  },
  selection: {
    type: Boolean,
    default: false,
  },
  columns: {
    type: Array,
    default() {
      return []
    },
  },
  tableName: {
    type: String,
    default: '商品监控',
  },
  dataSource: {
    type: Array,
    default: [],
  },
  emptyText: {
    type: String,
    default: '暂无数据',
  },
  loading: {
    type: Boolean,
    default: false,
  },
  bordered: {
    type: Boolean,
    default: false,
  },
})
const showSettingPopover = ref(false)
const currColumns = ref(TableColumnConfig.getTableInfo(props.columns, props.tableName));
const changeColumn = () => {
  currColumns.value = TableColumnConfig.getTableInfo(props.columns, props.tableName);
}
watch(() => props.columns.value, () => {
  changeColumn();
}, {deep: true})
const emit = defineEmits([
  'selectionChange', 'update:selectedRows'
])
const multipleTableRef = ref()
watch(() => props.dataSource, (value) => {
  searchDataSource()
  calcCopyData()
  // 清空选中
  selectedRowKeys.value = []
}, {deep: true})
watch(categoryData, () => {
  calcCopyData()
}, {deep: true})
const data = ref([])
const id = ref(uid(32));
const searchDataSource = () => {
  return new Promise(_ => {
    if (searchValue.value) {
      data.value = props.dataSource.filter((item) => {
        return Object.values(item).some((value) => {
          if (typeof value === 'object') {
            value = JSON.stringify(value);
          }
          return String(value).indexOf(searchValue.value) > -1
        })
      })
    } else {
      data.value = props.dataSource
    }
  })

  // 使用异步非阻塞形式优化检索

}

const copyData = ref('')
const cpj = new ClipboardJS(`#cpbtn${id.value}`)
cpj.on('success', (e) => {
  message.success('复制成功')
})
const getSelectionRows = () => {
  return multipleTableRef.value?.getSelectionRows() || []
}
const searchValue = ref('')
const search = () => {
  searchDataSource()
  calcCopyData()
}
// watch(() => searchValue.value, () => {
//   searchDataSource()
//   calcCopyData()
// })
defineExpose({
  getSelectionRows,
})
const copyType = ref('1')
const excelType = ref('1')
const calcCopyData = () => {
  return new Promise(_ => {
    copyData.value = ''
    if (copyType.value === '1') {
      currColumns.value.forEach((item) => {
        if (typeof item.dataIndex !== 'undefined') {
          copyData.value += `${item.title}\t`
        }
      })
      copyData.value += '\n'
    }
    props.dataSource.forEach((item) => {
      currColumns.value.forEach((col) => {
        if (typeof col.export!=='undefined' && !col.export) {
          return;
        }
        if (typeof col.dataIndex !== 'undefined') {
          if (typeof col.render !== 'undefined') {
            copyData.value += col.render(getContent(item, col), item, col.dataIndex) + "\t"
          } else if (col.dataType === 'category') {
            copyData.value += `${typeof categoryData[getContent(item, col)] != 'undefined' ? categoryData[getContent(item, col)].name : '--'}\t`
          } else if (col.dataType === 'platform') {
            if (typeof item[col.dataIndex] != 'undefined') {
              copyData.value += `${getContent(item, col) ? '天猫' : '淘宝'}\t`
            } else {
              copyData.value += "未知\t"
            }
          } else if (col.dataType === 'product') {
            copyData.value += getContent(item, {
              dataIndex: col.dataField.item_title,
            }).replace(/[\r\n]/g, '') + "\t"
          } else if (col.dataType === 'shop') {
            copyData.value += getContent(item, {
              dataIndex: col.dataField.shop_title,
            }).replace(/[\r\n]/g, '') + "\t"
          } else {
            copyData.value += `${getContent(item, col)}\t`
          }
        }
      })
      copyData.value += '\n'
    })
  });
}
const getContent = (record, column) => {
  // (column.dataIndex.split('.').length > 1 ? record[column.dataIndex.split('.')[0]][column.dataIndex.split('.')[1]] : record[column.dataIndex]) || '--'
  if (typeof column.dataIndex == 'undefined') {
    return '--'
  }
  let dataIndexs = column.dataIndex.split('.')
  if (dataIndexs.length > 1) {
    // 多层对象处理 例如：item.item_title item.user.nick
    if (dataIndexs.length === 2) {
      if (typeof record[dataIndexs[0]] == 'undefined') {
        return '--'
      }
      if (record[dataIndexs[0]]) {
        return record[dataIndexs[0]][dataIndexs[1]] || '--'
      } else {
        return '--'
      }
    } else if (dataIndexs.length === 3) {
      if (typeof record[dataIndexs[0]] == 'undefined' || !record[dataIndexs[0]]) {
        return '--'
      }
      if (typeof record[dataIndexs[0]][dataIndexs[1]] == 'undefined' || !record[dataIndexs[0]][dataIndexs[1]]) {
        return '--'
      }
      return record[dataIndexs[0]][dataIndexs[1]][dataIndexs[2]] || '--'
    } else if (dataIndexs.length === 4) {
      if (typeof record[dataIndexs[0]] == 'undefined') {
        return '--'
      }
      if (typeof record[dataIndexs[0]][dataIndexs[1]] == 'undefined') {
        return '--'
      }
      if (typeof record[dataIndexs[0]][dataIndexs[1]][dataIndexs[2]] == 'undefined') {
        return '--'
      }
      return record[dataIndexs[0]][dataIndexs[1]][dataIndexs[2]][dataIndexs[3]] || '--'
    }
  } else {
    if (typeof record[column.dataIndex] == 'undefined' || record[column.dataIndex] === null) {
      return '--'
    } else {
      return record[column.dataIndex]
    }
  }
}
searchDataSource()
calcCopyData()
const exportExcel = () => {
  const ws = {}
  const wb = {
    SheetNames: [],
    Sheets: {},
  }
  // 加入表头
  const headers = currColumns.value.map((item) => {
    if (typeof item.dataIndex !== 'undefined') {
      return item
    }
  }).filter((item) => {
    return typeof item !== 'undefined'
  })
  utils.sheet_add_json(ws, [...props.dataSource.map((item) => {
    const row = {}
    headers.map((col) => {
      if (typeof col.export!=='undefined' && !col.export) {
        return;
      }
      if (typeof col.dataType !== 'undefined') {
        if (typeof col.render !== 'undefined') {
          row[col.title] = col.render(getContent(item, col), item)
        } else if (col.dataType === 'category') {
          row[col.title] = `${typeof categoryData[getContent(item, col)] != 'undefined' ? categoryData[getContent(item, col)].name : '--'}`
        } else if (col.dataType === 'platform') {
          if (typeof item[col.dataIndex] != 'undefined') {
            row[col.title] = `${item[col.dataIndex] ? '天猫' : '淘宝'}`
          } else {
            row[col.title] = '未知'
          }
        } else if (col.dataType === 'product') {
          row[col.title] = getContent(item, {
            dataIndex: col.dataField.item_title,
          }).replace(/[\r\n]/g, '')
        } else if (col.dataType === 'shop') {
          row[col.title] = getContent(item, {
            dataIndex: col.dataField.shop_title,
          }).replace(/[\r\n]/g, '')
        } else if (col.dataType === 'time') {
          row[col.title] = item[col.dataIndex] ? moment(item[col.dataIndex]).format('YYYY-MM-DD HH:mm:ss') : '--'
        } else if (col.dataType === 'customRender') {
          row[col.title] = col.render(getContent(item, col), item)
        } else {
          let content = getContent(item, col)
          if (typeof content == "object") {
            if (content instanceof Array) {
              row[col.title] = content.join("\n")
            } else {
              row[col.title] = JSON.stringify(content)
            }
          } else {
            row[col.title] = content
          }
        }
      } else {
        let content = getContent(item, col)
        if (typeof content == "object") {
          if (content instanceof Array) {
            row[col.title] = content.join("\n")
          } else {
            row[col.title] = JSON.stringify(content)
          }
        } else {
          row[col.title] = content
        }
      }
    })
    return row
  })])
  utils.book_append_sheet(wb, ws, 'Sheet1')
  writeFileXLSX(wb, `[星察数据]${props.tableName}_${moment().format('YYYYMMDDHHmmss')}.${excelType.value === '1' ? 'xlsx' : 'csv'}`)
}
onMounted(() => {
  calcCopyData()
})
const selectedRowKeys = ref([]);
const onChange = (rowKeys, selectedRows) => {
  selectedRowKeys.value = rowKeys
  emit('update:selectedRows', selectedRows)
  emit('selectionChange', selectedRows)
  // console.log(`selectedRowKeys: ${rowKeys}`, 'selectedRows: ', selectedRows);
}
watch(() => props.selectedRows, (value) => {
  if (value !== false) {
    selectedRowKeys.value = value.map((item) => {
      return item[props.rowKey]
    })
  }
}, {deep: true})
onBeforeUnmount(() => {
  try {
    cpj.destroy()
  } catch (e) {
  }
})

// 获取 付款人数 
const getRealSales = (e) => {
  return e.realSales ? parseInt(e.realSales.match(/\d+/)[0]) : 0
}
</script>

<template>
  <div style="background: #f9f9f9;padding-top: 10px;border: 1px solid rgb(245, 245, 245);border-radius: 7px;"
       class="xc-table"
  >
    <textarea :id="`copy${id}`" style="display: block;z-index: -9;position:absolute;opacity: 0;"
    >{{ copyData }}</textarea>
    <slot name="header">
      <a-row class="mb-3 group" justify="space-between" type="flex" style="padding: 0 10px;">
        <a-col flex="1">
          <slot name="toolbar"/>
        </a-col>

        <a-col>
          <a-space>
            <div class="w-36 inline-block" style="padding-right: 1rem;width: 160px;">
              <a-input-search v-model:value="searchValue" @search="search" size="small" placeholder="全局搜索">
              </a-input-search>
            </div>
            <div class="ml-2 inline-block">
              <a-dropdown-button size="small">
                <div :id="`cpbtn${id}`" class="text-xs" :data-clipboard-target="`#copy${id}`">
                  <i class="i-ep-document-copy mr-1"/>复制数据
                </div>
                <template #icon>
                  <DownOutlined style="font-size: 10px;"/>
                </template>
                <template #overlay style="width: 180px;">
                  <a-menu style="width: 180px;">
                    <a-menu-item @click="copyType = '0'">
                      <a-row type="flex" class="text-gray[500]">
                        <a-col flex="1">
                          <div class="text-xs">
                            复制表格 数据
                          </div>
                        </a-col>
                        <a-col>
                          <div
                              class="text-xs" :style="{
                        color: copyType === '0' ? '#1890ff' : '',
                      }"
                          >
                            默认
                            <CheckCircleOutlined/>
                          </div>
                        </a-col>
                      </a-row>
                    </a-menu-item>
                    <!--              <a-menu-item><span class="text-xs">复制表格 数据+图片</span></a-menu-item> -->
                    <!--              <a-menu-item><span class="text-xs">复制表格 数据+图片链接</span></a-menu-item> -->
                    <a-menu-item @click="copyType = '1'">
                      <a-row class="text-gray[500]">
                        <a-col flex="1">
                          <div class="text-xs">
                            复制表格 表头+数据
                          </div>
                        </a-col>
                        <a-col>
                          <div
                              class="text-xs" :style="{
                        color: copyType === '1' ? '#1890ff' : '',
                      }"
                          >
                            默认
                            <CheckCircleOutlined/>
                          </div>
                        </a-col>
                      </a-row>
                    </a-menu-item>
                    <!--              <a-menu-item><span class="text-xs">复制表格 表头+数据+图片</span></a-menu-item> -->
                    <!--              <a-menu-item><span class="text-xs">复制表格 表头+数据+图片链接</span></a-menu-item> -->
                  </a-menu>
                </template>
              </a-dropdown-button>
            </div>
            <div class="ml-2 inline-block">
              <a-dropdown-button size="small">
                <div class="text-xs" @click="exportExcel">
                  <i class="i-ep-download mr-1"/>导出表格
                </div>
                <template #icon>
                  <DownOutlined style="font-size: 10px;"/>
                </template>
                <template #overlay>
                  <a-menu style="width: 200px;">
                    <a-menu-item @click="excelType = '0'">
                      <a-row type="flex" class="text-gray[500]">
                        <a-col flex="1">
                          <div class="text-xs">
                            复制表格 csv
                          </div>
                        </a-col>
                        <a-col>
                          <div
                              class="text-xs" :style="{
                        color: excelType === '0' ? '#1890ff' : '',
                      }"
                          >
                            默认
                            <CheckCircleOutlined/>
                          </div>
                        </a-col>
                      </a-row>
                    </a-menu-item>
                    <a-menu-item @click="excelType = '1'">
                      <a-row type="flex" class="text-gray[500]">
                        <a-col flex="1">
                          <div class="text-xs">
                            复制表格 xlsx
                          </div>
                        </a-col>
                        <a-col>
                          <div
                              class="text-xs" :style="{
                        color: excelType === '1' ? '#1890ff' : '',
                      }"
                          >
                            默认
                            <CheckCircleOutlined/>
                          </div>
                        </a-col>
                      </a-row>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown-button>
            </div>
            <div class="ml-2 inline-block">
              <a-popover v-model:open="showSettingPopover" placement="bottomRight" trigger="click">
                <a-button size="small" type="default">
                  <SettingOutlined/>
                  设置
                </a-button>
                <template #content>
                  <TableColumnSeting :columns="columns" :table-name="tableName" @refresh="()=>{
                    changeColumn()
                    showSettingPopover = false
                  }"
                  />
                </template>
              </a-popover>
            </div>
          </a-space>

        </a-col>
      </a-row>
    </slot>
    <slot name="table">
      <a-table 
        :loading="loading" 
        :pagination="pagination ? { defaultPageSize: 20,showTotal: ((total) => {return (selection?`已选择 ${selectedRowKeys.length} 条，`:'')+`共 ${total} 条`;}),} : false" 
        :columns="currColumns.filter((_)=>_.show)" 
        ref="multipleTableRef" 
        :size="size"
        :scroll="{ ...scroll, y:pagination?scroll.y-50:scroll.y,}"
        :data-source="data"
        :row-key="rowKey"
        :row-selection="selectedRows!==false ? {selectedRowKeys: selectedRowKeys,onChange,} : false"
        :virtual-scroll="true"
        :bordered="bordered"
      >
        <template #bodyCell="{column,record,index}">
          <template v-if="typeof column.dataType !=='undefined' && column.dataType=='category'">
            <template v-if="typeof column.tooltip!=='undefined' && column.tooltip">
              <a-tooltip placement="top">
                <template #title>
                <span>{{
                    typeof categoryData[record[column.dataIndex]] != 'undefined' ? categoryData[record[column.dataIndex]].path.join('>') : '--'
                  }}</span>
                </template>
                <div class="text-ellipsis">
                  {{
                    typeof categoryData[record[column.dataIndex]] != 'undefined' ? categoryData[record[column.dataIndex]].name : '--'
                  }}
                </div>
              </a-tooltip>
            </template>
            <template v-else>
              {{
                typeof categoryData[record[column.dataIndex]] != 'undefined' ? categoryData[record[column.dataIndex]].name : '--'
              }}
            </template>
          </template>
          <template v-else-if="column.dataType=='realSales'">
              {{ getRealSales(record) }}
          </template>
          <template v-else-if="typeof column.dataType !=='undefined' && column.dataType=='time'">
            {{ moment(Number(getContent(record, column))).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template v-else-if="typeof column.dataType!='undefined' && column.dataType=='product'">
            <a-row type="flex">
              <a-col>
                <a-image
                    :src="getContent(record,{
                    dataIndex: column.dataField['item_pic'],
                  })"
                    :width="30"
                    :height="30"
                />
              </a-col>
              <a-col flex="1" style="width: calc(100% - 30px)">
                <a type="link" target="_blank"
                   :href="`https://item.taobao.com/item.htm?id=${getContent(record,{
                    dataIndex: column.dataField['item_id'],
                  })}`"
                   style="margin-left: 10px;color: #1890ff;font-size: 12px;display: inline-block;line-height: 30px;"
                   class="text-ellipsis"
                   v-if="typeof column.dataField['item_id']!=='undefined' && column.dataField['item_id']"
                >
                  {{
                    getContent(record, {
                      dataIndex: column.dataField['item_title'],
                    }).replace(/<[^>]+>/g, '')
                  }}
                </a>
                <a type="link" target="_blank"
                   :href="`${getContent(record,{
                    dataIndex: column.dataField['item_url'],
                  })}`"
                   style="margin-left: 10px;color: #1890ff;font-size: 12px;display: inline-block;line-height: 30px;"
                   class="text-ellipsis"
                   v-else-if="typeof column.dataField['item_url']!=='undefined' && column.dataField['item_url']"
                >
                  {{
                    getContent(record, {
                      dataIndex: column.dataField['item_title'],
                    }).replace(/<[^>]+>/g, '')
                  }}
                </a>
                <div class="text-ellipsis"
                     style="margin-left: 10px;font-size: 12px;display: inline-block;line-height: 30px;" v-else
                >
                  {{
                    getContent(record, {
                      dataIndex: column.dataField['item_title'],
                    }).replace(/<[^>]+>/g, '')
                  }}
                </div>
              </a-col>
            </a-row>
          </template>
          <template v-else-if="typeof column.dataType!='undefined' && column.dataType=='shop'">
            <a-row type="flex">
              <a-col v-if="typeof column.dataField['shop_pic']!=='undefined' && column.dataField['shop_pic']">
                <a-image
                    :src="getContent(record,{
                    dataIndex: column.dataField['shop_pic'],
                  })"
                    :width="30"
                    :height="30"
                />
              </a-col>
              <a-col flex="1" style="width: calc(100% - 30px)">
                <a type="link" target="_blank"
                   :href="`${getContent(record,{
                    dataIndex: column.dataField['shop_url'],
                  })}`"
                   style="margin-left: 10px;color: #1890ff;font-size: 12px;display: inline-block;line-height: 30px;"
                   class="text-ellipsis"
                   v-if="typeof column.dataField['shop_url']!=='undefined' && column.dataField['shop_url']"
                >
                  {{
                    getContent(record, {
                      dataIndex: column.dataField['shop_title'],
                    }).replace(/<[^>]+>/g, '')
                  }}
                </a>
                <div class="text-ellipsis"
                     style="margin-left: 10px;font-size: 12px;display: inline-block;line-height: 30px;" v-else
                >
                  {{
                    getContent(record, {
                      dataIndex: column.dataField['shop_title'],
                    }).replace(/<[^>]+>/g, '')
                  }}
                </div>
              </a-col>
            </a-row>
          </template>
          <template v-else-if="typeof column.dataType!='undefined' && column.dataType=='brand'">
            <a-row type="flex">
              <a-col v-if="typeof column.dataField['brand_logo']!=='undefined' && column.dataField['brand_logo']">
                <a-image
                    :src="'//img.alicdn.com/tps/'+(getContent(record,{
                    dataIndex: column.dataField['brand_logo'],
                  })==='--'?'TB1P1W_LXXXXXXoXVXXXXXXXXXX-74-74.png':getContent(record,{
                    dataIndex: column.dataField['brand_logo'],
                  }))+'_48x48.jpg'"
                    :width="30"
                    :height="30"
                />
              </a-col>
              <a-col flex="1" style="width: calc(100% - 30px)">
                <div class="text-ellipsis"
                     style="margin-left: 10px;font-size: 12px;display: inline-block;line-height: 30px;"
                >
                  {{
                    getContent(record, {
                      dataIndex: column.dataField['brand_name'],
                    }).replace(/<[^>]+>/g, '')
                  }}
                </div>
              </a-col>
            </a-row>
          </template>
          <template v-else-if="typeof column.dataType!='undefined' && column.dataType=='platform'">
          <span v-if="typeof record[column.dataIndex]!=='undefined'">
            {{
              record[column.dataIndex] ? '天猫' : '淘宝'
            }}
          </span>
            <span v-else>
            --
          </span>
          </template>
          <template v-else-if="typeof column.dataType!='undefined' && column.dataType=='images'">
            <a-image-preview-group
              v-if="(record[typeof column.dataField=='undefined'?column.dataIndex:column.dataField]||[]).length>0"
            >
              <a-row :gutter="[5,5]">
                <a-col 
                  v-for="img in record[typeof column.dataField=='undefined'?column.dataIndex:column.dataField]"
                  :span="6"
                  :key="img"
                >
                  <a-image :src="`${img}_sum.jpg`" style="width: 100%;" :preview="{src: img}" />
                </a-col>
              </a-row>
            </a-image-preview-group>
            <div v-else>--</div>
          </template>
          <template v-else-if="typeof column.dataType!='undefined' && column.dataType==='custom'">
            <slot :name="column.slot" v-bind="record"></slot>
          </template>
          <template v-else-if="typeof column.dataType!='undefined' && column.dataType==='customRender'">
            {{ column.render(getContent(record, column), record, column.dataIndex) }}
          </template>
          <template v-else-if="typeof column.dataIndex!=='undefined'">
            <!--          tooltip-->
            <template v-if="typeof column.tooltip!=='undefined' && column.tooltip">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ getContent(record, column) }}</span>
                </template>
                <div class="text-ellipsis">
                  {{ getContent(record, column) }}
                </div>
              </a-tooltip>
            </template>
            <template v-else>
              {{ getContent(record, column) }}
            </template>
          </template>
        </template>
        <template #footer>
          <slot name="footer">
          </slot>
        </template>
      </a-table>
    </slot>
  </div>
</template>
<style lang="less" scoped>
// 一行 超出隐藏

.text-ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  width: 100%;
}

.text-xs {
  font-size: 12px;
}
</style>
<style lang="less">
.xc-table {
  .xc-ant-spin-container {
    .xc-ant-pagination {
      padding: 0 10px;
      margin-top: 0 !important;
    }
  }
}
</style>
